//
//  XGBaseNavigationViewController.m
//  Lottery
//
//  Created by monkey on 2018/9/25.
//  Copyright © 2018 itcast. All rights reserved.
//
#import <objc/runtime.h>

#import "XGBaseNavigationViewController.h"

@interface XGBaseNavigationViewController () <UIGestureRecognizerDelegate>

@end

@implementation XGBaseNavigationViewController

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 添加手势
    [self addGestureRecognizer];
    
    // 设置导航栏穿透效果
    self.navigationBar.translucent = YES;
    
    UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[self class]]];
    navBar.tintColor = [UIColor darkGrayColor];
}

- (void)addGestureRecognizer
{
    /*
      <UIScreenEdgePanGestureRecognizer: 0x7f8e9c636690; state = Possible; delaysTouchesBegan = YES; view = <UILayoutContainerView 0x7f8e9c633cf0>; target= <(action=handleNavigationTransition:, target=<_UINavigationInteractiveTransition 0x7f8e9c635ef0>)>>
     */
    // NSLog(@"%@",self.interactivePopGestureRecognizer);
    
    // 使用运行时 获取UIScreenEdgePanGestureRecognizer手势的target runtime只能获取本类的成员变量 无法获取子类及父类的成员变量
    
    /*
    unsigned int count = 0;
    Ivar *var = class_copyIvarList([UIGestureRecognizer class], &count);
    for (int i = 0; i < count; i++) {
        NSString *name = [NSString stringWithUTF8String:ivar_getName(var[i])];
        NSLog(@"%@",name);
    }
    
    free(var); */
    
    // 存放target的属性是 _targets  这是一个数组 数组里的每个元素是一个target
    // (action=handleNavigationTransition:, target=<_UINavigationInteractiveTransition 0x7fabebd09ee0>)
    // NSLog(@"%@",[[self.interactivePopGestureRecognizer valueForKey:@"_targets"] lastObject]);
    
    id target = [[self.interactivePopGestureRecognizer valueForKey:@"_targets"] lastObject];
    
    // 禁用系统手势
    self.interactivePopGestureRecognizer.enabled = NO;
    
    // 添加手势 实现全屏滑动返回功能
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wundeclared-selector"
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:[target valueForKey:@"target"] action:@selector(handleNavigationTransition:)];
    #pragma clang diagnostic pop

    pan.delegate = self;
    [self.view addGestureRecognizer:pan];
}

#pragma mark - 重写方法

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    // 如果不是非根控制器 push的时候隐藏底部tabBar
    if (self.childViewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    
    [super pushViewController:viewController animated:animated];
}

#pragma mark - UIGestureRecognizerDelegate

// 手势是否可用 如果是根控制器禁用滑动返回 如果是非根控制器 手势可用
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return self.childViewControllers.count > 1;
}

@end
